package org.osami.gateway.alarm;

import java.util.Date;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;

public class AlarmImpl implements IAlarm {

    private final String m_identifier;
    private final Date m_date;
    private final String m_message;
    private final Severity m_severity;

    private static final String SEPARATOR = "|";

    public AlarmImpl(Dictionary<String, Object> properties) {
        m_identifier = getAndCheckProperty(properties, ID_PROPERTY,
                String.class);
        m_date = getAndCheckProperty(properties, DATE_PROPERTY, Date.class);
        m_message = getAndCheckProperty(properties, MESSAGE_PROPERTY,
                String.class);
        m_severity = getAndCheckProperty(properties, SEVERITY_PROPERTY,
                Severity.class);
    }

    public AlarmImpl(String identifier, Date date, String message,
            Severity severity) {
        m_identifier = identifier;
        m_date = date;
        m_message = message;
        m_severity = severity;
    }

    public String getIdentifier() {
        return m_identifier;
    }

    public Date getDate() {
        // Return an independent instance, as Date is not immutable.
        return new Date(m_date.getTime());
    }

    public String getMessage() {
        return m_message;
    }

    public Severity getSeverity() {
        return m_severity;
    }

    public Map<String, Object> toProperties() {
        Map<String, Object> props = new HashMap<String, Object>();
        props.put(ID_PROPERTY, getIdentifier());
        props.put(DATE_PROPERTY, getDate());
        props.put(MESSAGE_PROPERTY, getMessage());
        props.put(SEVERITY_PROPERTY, getSeverity());
        return props;
    }

    private static <T> T getAndCheckProperty(Dictionary<String, Object> properties,
            String key, Class<T> type) {
        Object value = properties.get(key);
        if (value == null) {
            throw new IllegalArgumentException("Missing required property : "
                    + key);
        } else if (!type.isInstance(value)) {
            throw new IllegalArgumentException("Malformed property : " + key
                    + " (expecting " + type.getName() + ", have "
                    + value.getClass().getName() + ")");
        }
        return type.cast(value);
    }

    @Override
    public String toString() {
        return getIdentifier() + SEPARATOR + getDate() + SEPARATOR + getSeverity() + SEPARATOR + getMessage();
    }
}
